<template>
  <div class="search">
    <Card v-show="currView=='add'||currView=='edit'">
      <div slot="title">
        <a @click="close" class="back-title">
          <Icon type="ios-arrow-back" style="margin: 0 0 2px 0"/>返回
        </a>
      </div>
      <Row>
        <Form ref="form" :model="form" :label-width="100" :rules="formValidate" style="position:relative">
          <FormItem label="新闻标题" prop="title" >
            <Input
                    v-model="form.title"
                    maxlength="100"
                    show-word-limit
                    clearable
                    placeholder="请输入新闻标题"
                    style="width:450px"/>
          </FormItem>
          <FormItem label="新闻类型" prop="type" style="width:700px" >
            <RadioGroup v-model="form.type" >
              <Radio label="0">通知公告</Radio>
              <Radio label="1">新闻动态</Radio>
              <Radio label="2">法律法规</Radio>
              <Radio label="3">考核依据</Radio>
              <Radio label="4">一河一策</Radio>
              <Radio label="5">轮播图</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem v-show="form.type == '5'" label="图片地址" prop="img" >
            <upload-pic-input v-model="form.img" style="width:450px;" readonly></upload-pic-input>
          </FormItem>
          <FormItem label="是否展示" prop="flag" style="width:350px">
            <i-switch v-model="form.flag" true-value="1" false-value="0">
            </i-switch>
          </FormItem>
          <FormItem v-show="form.type != '5'" label="内容" prop="content" >
            <editor v-model="form.content" ref="editor"></editor>
          </FormItem>
          <Form-item>
            <Button
                    @click="handleSubmit"
                    :loading="submitLoading"
                    type="primary"
                    style="margin-right:5px"
            >提交并保存</Button>
          </Form-item>
        </Form>

<!--          <Button type="text" @click="modalVisible=false">取消</Button>-->
<!--          <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>-->
      </Row>

    </Card>
    <Card v-show="currView=='index'">
        <Row @keydown.enter.native="handleSearch">
          <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
            <Form-item label="新闻标题" prop="title">
              <Input type="text" v-model="searchForm.title" placeholder="请输入新闻标题" clearable style="width: 200px"/>
            </Form-item>
            <Form-item label="新闻类型" prop="type">
              <Select v-model="searchForm.type" placeholder="请选择" clearable style="width: 200px">
                  <Option value="0">通知公告</Option>
                  <Option value="1">新闻动态</Option>
                  <Option value="2">法律法规</Option>
                  <Option value="3">考核依据</Option>
                  <Option value="4">一河一策</Option>
                  <Option value="5">轮播图</Option>
              </Select>
            </Form-item>
            <Form-item label="展示状态" prop="flag">
                  <Select v-model="searchForm.flag" placeholder="请选择" clearable style="width: 200px">
                      <Option value="1">启用</Option>
                      <Option value="0">未启用</Option>
                  </Select>
                </Form-item>
            <Form-item label="内容" prop="content">
                  <Input type="text" v-model="searchForm.content" placeholder="请输入内容" clearable style="width: 200px"/>
                </Form-item>
            <Form-item style="margin-left:-35px;" class="br">
              <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
              <Button @click="handleReset">重置</Button>

            </Form-item>
          </Form>
        </Row>
        <Row class="operation">
          <Button @click="add" type="primary" icon="md-add">添加</Button>
          <Button @click="delAll" icon="md-trash">批量删除</Button>
          <Button @click="getDataList" icon="md-refresh">刷新</Button>
        </Row>
        <Row>
          <Alert show-icon>
            已选择 <span class="select-count">{{selectCount}}</span> 项
            <a class="select-clear" @click="clearSelectAll">清空</a>
          </Alert>
        </Row>
        <Row>
          <Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort" @on-selection-change="changeSelect"></Table>
        </Row>
        <Row type="flex" justify="end" class="page">
          <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
        </Row>
        <Modal v-model="picVisible" title="图片预览" footer-hide draggable >
            <img :src="infoForm.avatar" alt="无效的图片链接" style="width: 100%;margin: 0 auto;display: block;">
        </Modal>
      </Card>
  </div>
</template>

<script>
  import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
  import editor from "@/views/my-components/xboot/editor";
  export default {
    name: "Information",
    components: {
      uploadPicInput,
      editor
    },
    data() {
      return {
          picVisible: false, // 图片预览
          infoForm: {},
        currView:"index",
        loading: true, // 表单加载状态
        modalType: 0, // 添加或编辑标识
        modalVisible: false, // 添加或编辑显示
        modalTitle: "", // 添加或编辑标题
        searchForm: { // 搜索框初始化对象
          pageNumber: 1, // 当前页数
          pageSize: 10, // 页面大小
          sort: "create_time", // 默认排序字段
          order: "desc", // 默认排序方式
        },
        form: { // 添加或编辑表单对象初始化数据
          title: "",
          img: "",
          type: "0",
          flag: "1",
          content: '',
        },
        // 表单验证规则
        formValidate: {
          title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
          type: [{ required: true, message: "新闻类型不能为空", trigger: "blur" }],
        },
          formImgValidate: {
              title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
              type: [{ required: true, message: "新闻类型不能为空", trigger: "blur" }],
              img: [{ required: true, message: "请上传一张图片", trigger: "blur" }],
          },
          formContentValidate: {
              title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
              type: [{ required: true, message: "新闻类型不能为空", trigger: "blur" }],
              content: [{ required: true, message: "请填写新闻内容", trigger: "blur" }],
          },
        submitLoading: false, // 添加或编辑提交状态
        selectList: [], // 多选数据
        selectCount: 0, // 多选计数
        columns: [
          // 表头
          {
            type: "selection",
            width: 60,
            align: "center"
          },
          {
              title: "序号",
            type: "index",
            width: 70,
            align: "center"
          },
          {
            title: "新闻标题",
            key: "title",
            minWidth: 120,
              align: "center",
            sortable: false,
          },
            {
                title: "创建人",
                key: "createBy",
                minWidth: 60,
                align: "center",
                sortable: false,
            },
          /*{
            title: "图片",
            key: "img",
            minWidth: 120,
            sortable: false,
              render: (h, params) => {
                  if (params.row.type == "5") {
                      return h("img", {
                          attrs: {
                              src: params.row.img,
                              alt: "加载图片失败"
                          },
                          style: {
                              cursor: "pointer",
                              width: "120px",
                              height: "40px",
                              "margin-top": "5px",
                              "object-fit": "contain"
                          },
                          on: {
                              click: () => {
                                  this.showPic(params.row);
                              }
                          }
                      });
                  }else{
                      return params.row.content
                  }
              }
          },*/
          {
            title: "新闻类型",
            key: "type",
              align: "center",
            minWidth: 120,
            sortable: false,
              render: (h, params) => {
                let text = "";
                let color = "";
                  if (params.row.type == "0") {
                      text = "通知公告";
                      color = "volcano";
                  } else if (params.row.type == "1") {
                      text = "新闻动态";
                      color = "orange";
                  } else if (params.row.type == "2") {
                      text = "法律法规";
                      color = "cyan";
                  } else if (params.row.type == "3") {
                      text = "考核依据";
                      color = "blue";
                  }else if (params.row.type == "4") {
                      text = "一河一策";
                      color = "geekblue";
                  }else if (params.row.type == "5") {
                      text = "轮播图";
                      color = "purple";
                  }
                      return h("div", [
                          h("Tag", {
                              props: {
                                  color: color,
                              },
                          },
                              text
                          )
                      ]);

              },
          },
          {
            title: "展示状态",
            key: "flag",
            minWidth: 70,
              align: "center",
            sortable: false,
              render: (h, params) => {
                  if (params.row.flag == "1") {
                      return h("div", [
                          h("Badge", {
                              props: {
                                  status: "success",
                                  text: "正常展示"
                              }
                          })
                      ]);
                  } else if (params.row.flag == "0") {
                      return h("div", [
                          h("Badge", {
                              props: {
                                  status: "error",
                                  text: "不进行展示"
                              }
                          })
                      ]);
                  }
              },
          },
          {
            title: "内容",
            key: "content",
            minWidth: 120,
              align: "center",
              sortable: false,
              render: (h, params) => {
                  if (params.row.type == "5") {
                      return h("img", {
                          attrs: {
                              src: params.row.img,
                              alt: "加载图片失败"
                          },
                          style: {
                              cursor: "pointer",
                              width: "120px",
                              height: "40px",
                              "margin-top": "5px",
                              "object-fit": "contain"
                          },
                          on: {
                              click: () => {
                                  this.showPic(params.row);
                              }
                          }
                      });
                  }else{
                      return h("div", [
                          h("span", {

                          },
                              "点击编辑查看详情"
                          )
                      ]);
                  }
              }
          },
            {
                title: "发布时间",
                key: "createTime",
                align: "center",
                width: 200,
            },
          {
            title: "操作",
            key: "action",
            align: "center",
            width: 170,
            render: (h, params) => {
              return h("div", [
                h(
                        "Button",
                        {
                          props: {
                            type: "primary",
                            size: "small",
                            icon: "ios-create-outline"
                          },
                          style: {
                            marginRight: "5px"
                          },
                          on: {
                            click: () => {
                              this.edit(params.row);
                            }
                          }
                        },
                        "编辑"
                ),
                h(
                        "Button",
                        {
                          props: {
                            type: "error",
                            size: "small",
                            icon: "md-trash"
                          },
                          on: {
                            click: () => {
                              this.remove(params.row);
                            }
                          }
                        },
                        "删除"
                )
              ]);
            }
          }
        ],
        data: [], // 表单数据
        total: 0 // 表单数据总数
      };
    },
    methods: {
      init() {
        this.getDataList();
      },
      changePage(v) {
        this.searchForm.pageNumber = v;
        this.getDataList();
        this.clearSelectAll();
      },
      changePageSize(v) {
        this.searchForm.pageSize = v;
        this.getDataList();
      },
      handleSearch() {
        this.searchForm.pageNumber = 1;
        this.searchForm.pageSize = 10;
        this.getDataList();
      },
      handleReset() {
        this.$refs.searchForm.resetFields();
        this.searchForm.pageNumber = 1;
        this.searchForm.pageSize = 10;
        // 重新加载数据
        this.getDataList();
      },
        showPic(v) {
            this.infoForm.avatar = v.img;
            this.picVisible = true;
        },
      changeSort(e) {
        this.searchForm.sort = e.key;
        this.searchForm.order = e.order;
        if (e.order === "normal") {
          this.searchForm.order = "";
        }
        this.getDataList();
      },
      clearSelectAll() {
        this.$refs.table.selectAll(false);
      },
      changeSelect(e) {
        this.selectList = e;
        this.selectCount = e.length;
      },

      getDataList() {
        this.loading = true;
        // 带多条件搜索参数获取表单数据 请自行修改接口
        this.getRequest("/information/getByCondition", this.searchForm).then(res => {
          this.loading = false;
          if (res.success) {
            this.data = res.result.records;
            this.total = res.result.total;
          }
        });

      },
      handleSubmit() {
          let that = this;
          if("5" == that.form.type){
              that.formValidate = that.formImgValidate;
          }else {
              that.formValidate = that.formContentValidate;
          }
        this.$refs.form.validate(valid => {
          if (valid) {
            this.submitLoading = true;
            if (this.modalType === 0) {
              // 添加 避免编辑后传入id等数据 记得删除
              delete this.form.id;
              this.postRequest("/information/insertOrUpdate", this.form).then(res => {
                this.submitLoading = false;
                if (res.success) {
                  this.$Message.success("操作成功");
                  this.getDataList();
                  this.modalVisible = false;
                  this.close();
                }
              });

            } else {
              // 编辑
              this.postRequest("/information/insertOrUpdate", this.form).then(res => {
                this.submitLoading = false;
                if (res.success) {
                  this.$Message.success("操作成功");
                  this.getDataList();
                  this.close();
                }
              });

            }
          }
        });
      },
      add() {
        this.modalType = 0;
        this.modalTitle = "添加";
        this.$refs.form.resetFields();
          this.$refs.editor.setData("");
        delete this.form.id;
        this.currView = "add";
      },
      close(){
        this.currView = "index";
      },
      edit(v) {
        this.modalType = 1;
        this.modalTitle = "编辑";
        // 转换null为""
        for (let attr in v) {
          if (v[attr] === null) {
            v[attr] = "";
          }
        }
        let str = JSON.stringify(v);
        let data = JSON.parse(str);
        this.form = data;
        this.$refs.form.resetFields();
        this.$refs.editor.setData(data.content);
        this.currView = "edit";
      },
      remove(v) {
        this.$Modal.confirm({
          title: "确认删除",
          // 记得确认修改此处
          content: "您确认要删除 " + v.title + " ?",
          loading: true,
          onOk: () => {
            // 删除
            this.deleteRequest("/information/delByIds/" + v.id).then(res => {
              this.$Modal.remove();
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
              }
            });
          }
        });
      },
      delAll() {
        if (this.selectCount <= 0) {
          this.$Message.warning("您还未选择要删除的数据");
          return;
        }
        this.$Modal.confirm({
          title: "确认删除",
          content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
          loading: true,
          onOk: () => {
            let ids = "";
            this.selectList.forEach(function(e) {
              ids += e.id + ",";
            });
            ids = ids.substring(0, ids.length - 1);
            // 批量删除
            this.deleteRequest("/information/delByIds/" + ids).then(res => {
              this.$Modal.remove();
              if (res.success) {
                this.$Message.success("操作成功");
                this.clearSelectAll();
                this.getDataList();
              }
            });
          }
        });
      }
    },
    mounted() {
      this.init();
    }
  };
</script>
<style lang="less">
  .search {
  .operation {
    margin-bottom: 2vh;
  }
  .select-count {
    font-size: 13px;
    font-weight: 600;
    color: #40a9ff;
  }
  .select-clear {
    margin-left: 10px;
  }
  .page {
    margin-top: 2vh;
  }
  }
</style>